package org.example.protocol;

import io.vertx.core.buffer.Buffer;
import org.example.serializer.Serializer;
import org.example.serializer.SerializerFactory;

import java.io.IOException;

/**
 * 协议消息编码器
 */
public class ProtocolMessageEncoder {

    /**
     * 编码
     *
     * @param protocolMessage
     * @return
     */
    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException {
        //判断protocolMessage是否为空，或者protocolMessage的header是否为空
        if (protocolMessage == null || protocolMessage.getHeader() == null) {
            //如果为空，则返回一个空的Buffer
            return Buffer.buffer();
        }
        //获取protocolMessage的header
        ProtocolMessage.Header header = protocolMessage.getHeader();
        //依次向缓冲区写入字节
        Buffer buffer = Buffer.buffer();
        //写入magic
        buffer.appendByte(header.getMagic());
        //写入version
        buffer.appendByte(header.getVersion());
        //写入serializer
        buffer.appendByte(header.getSerializer());
        //写入type
        buffer.appendByte(header.getType());
        //写入status
        buffer.appendByte(header.getStatus());
        //写入requestId
        buffer.appendLong(header.getRequestId());
        //获取序列化器
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByKey(header.getSerializer());
        //如果序列化协议不存在，则抛出异常
        if (serializerEnum == null) {
            throw new RuntimeException("序列化协议不存在");
        }
        //获取序列化器实例
        Serializer serializer = SerializerFactory.getInstance(serializerEnum.getValue());
        //序列化body
        byte[] bodyBytes = serializer.serialize(protocolMessage.getBody());
        //写入body长度和数据
        buffer.appendInt(bodyBytes.length);
        buffer.appendBytes(bodyBytes);
        //返回缓冲区
        return buffer;
    }


}
